﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MossmanMill.DataModel;

namespace MossmanMill.View
{
    [ToolboxItem(true)]
    [ToolboxBitmap(typeof(SlotSelect))]
    public class SlotSelect : Panel
    {
        private readonly Pen brush;
        private readonly Font font;
        private readonly Rectangle[] slotRectangles;
        //private Rack rack;


        public int Slot { get; set; }

        [Bindable(true), Category("Color Options"),
        Description("The color for the selected slot")]
        public Brush SelectionBrush { get; set; }

        [Bindable(true), Category("Color Options"),
        Description("The border color for the slots")]
        public Brush BorderBrush { get; set; }

        [Bindable(true), Category("Slot Options"),
        Description("If this slot is a processor slot"),
        DefaultValue(true)]
        public bool IsProcessor { get; set; }

        //TODO Slot Change Event
        [Bindable(true), Category("SlotSelect"),
        Description("Called when clicked")]
        public event EventHandler<EventArgs> SlotSelected;

        public SlotSelect()
        {
            SelectionBrush = Brushes.Blue;
            BorderBrush = Brushes.Black;
            Slot = 0;
            brush = new Pen(BorderBrush);
            slotRectangles = new Rectangle[13];
            for (var x = 0; x < 13; x++)
            {
                slotRectangles[x] = new Rectangle(x * 20, 0, 20, 40);
            }
            font = new Font("Arial", 8);
        }

        protected override void OnClick(EventArgs e)
        {
            var max = IsProcessor?11:12;
            var point = (MouseEventArgs)e;
            var slot = point.X / 20;
            if (slot > 12) return;
            Slot = slot;
            Invalidate();
            SlotSelected(this, EventArgs.Empty);
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            var g = e.Graphics;
            g.DrawRectangles(brush, slotRectangles);
            g.FillRectangle(SelectionBrush, slotRectangles[Slot]);
            if (IsProcessor && Slot < 12) g.FillRectangle(SelectionBrush, slotRectangles[Slot+1]);
            for (var x = 0; x < 13; x++)
            {
                var color = Brushes.Black;
                if (IsProcessor && x == Slot + 1) color = Brushes.White;
                if (x == Slot) color = Brushes.White;
                g.DrawString("" + x, font, color, x * 20 + 4, 4);
            }
        }
    }
}
